//
//  SYS_NicknameVC.m
//  System_App
//
//  Created by 伟徐 on 2017/11/28.
//  Copyright © 2017年 czy001. All rights reserved.
//

#import "SYS_NicknameVC.h"

@interface SYS_NicknameVC ()<UITextFieldDelegate,UIGestureRecognizerDelegate>

@property (nonatomic, strong) UITextField *nickTextFiled;
@property (nonatomic, strong) UILabel *restrictLabel;
@property (nonatomic, strong) UIButton *saveBtn;


@end

@implementation SYS_NicknameVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setNavigationBar];
    [self initMainView];
    
    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
    tap.numberOfTapsRequired=1;
    tap.delegate=self;
    [self.view addGestureRecognizer:tap];
    
}

#pragma mark -- InitMainView
-(void)initMainView{
    
    UIView *backView=[[UIView alloc]initWithFrame:CGRectMake(0, 12, SCREENWIDTH, 40)];
    backView.backgroundColor=[UIColor whiteColor];
    backView.userInteractionEnabled = YES;
    [self.view addSubview:backView];
    
    [self.view addSubview:self.nickTextFiled];
    [self.view addSubview:self.restrictLabel];
    [self.view addSubview:self.saveBtn];
    
    _nickTextFiled.text =_nickname;
    [_nickTextFiled mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(12);
        make.top.equalTo(self.view).offset(12);
        make.size.mas_equalTo(CGSizeMake(SCREENWIDTH-24, 40));
    }];
    
    [_restrictLabel sizeToFit];
    [_restrictLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(12);
        make.top.equalTo(_nickTextFiled.mas_bottom).offset(6);
    }];
    
    [_saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(20);
        make.top.equalTo(_restrictLabel.mas_bottom).offset(24);
        make.size.mas_equalTo(CGSizeMake(SCREENWIDTH-40, 48));
    }];
    
}

#pragma mark -- setter and getter
- (void)setNavigationBar{
    self.title = @"修改昵称";
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:@"SYS_Public_back" highImage:nil title:nil target:self action:@selector(nicknameVCBack)];
    self.view.backgroundColor =RGBACOLOR(240, 240, 240, 1);
}

-(void)nicknameVCBack{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)gotoAmendNickname{
    [self hideKeyboard];
    if(_nickname.length == 0){
        [MBProgressHUD showSuccess:@"昵称不能为空" toView:self.view];
        return;
    }
    
    if(_nickname.length > 20){
        [MBProgressHUD showSuccess:@"昵称超过限制,请重新输入!" toView:self.view];
        return;
    }
    
    NSString *session = [SYS_LoginModel instance].sessionInfo.session;
    UICKeyChainStore *keychainStore = [UICKeyChainStore keyChainStore];
    NSString *pid = [keychainStore stringForKey:@"pid"];
    NSDictionary *params =@{
                            @"nickName":_nickname,
                            @"pid":pid,
                            @"session":session
                            };
    NSString *url=[NSString stringWithFormat:@"%@/adm/sysapp/updateAdmInfo",SERVICE_IP];
    [self showHudInView:self.view hint:@"正在加载..."];
    [NetRequestClass NetRequestGETWithRequestURL:url WithParameter:params WithReturnValeuBlock:^(id returnValue) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        Dlog(@"+++++%@",returnValue);
        NSString *flag=returnValue[@"flag"];
        if ([flag isEqualToString:@"true"]) {
            [MBProgressHUD showSuccess:@"昵称修改成功!" toView:self.view];
            
            SYS_User *userModel=[SYS_LoginModel instance].user;
            userModel.nickName=_nickname;
            [SYS_LoginModel instance].user = userModel;
            
            //存储当前登录信息
            NSDictionary *diccc = [[SYS_LoginModel instance] dictionaryValueBy:[SYS_LoginModel instance]];
            NSFileManager * loginfileManager = [[NSFileManager alloc]init];
            [loginfileManager removeItemAtPath:LoginFilePath error:nil];
            [NSKeyedArchiver archiveRootObject:diccc toFile:LoginFilePath];
            
            if(self.saveClickBlock){
                self.saveClickBlock();
            }
            [self performSelector:@selector(nicknameVCBack) withObject:self afterDelay:1.5];
        }else{
            [MBProgressHUD showSuccess:returnValue[@"exp"] toView:self.view];
        }
       
    } WithErrorCodeBlock:^(id errorCode) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } WithFailureBlock:^{
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showSuccess:@"网络请求错误!" toView:self.view];
    }];
}

- (void)hideKeyboard{
    [_nickTextFiled resignFirstResponder];
}

#pragma mark UITextFieldDelegate
- (void)textFieldDidEndEditing:(UITextField *)textField{
    _nickname =textField.text;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self hideKeyboard];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;{
    
    NSString *tem = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]componentsJoinedByString:@""];

    if (![string isEqualToString:tem]){
 
        return NO;
    }
    return YES;
}

#pragma mark - 懒加载控件
-(UITextField *)nickTextFiled{
    if (!_nickTextFiled) {
        _nickTextFiled = [[UITextField alloc] init];
        _nickTextFiled.delegate=self;
        _nickTextFiled.backgroundColor =[UIColor whiteColor];
        [_nickTextFiled setValue:RGBACOLOR(190,189,189, 1) forKeyPath:@"_placeholderLabel.textColor"];
        _nickTextFiled.textAlignment =NSTextAlignmentLeft;
        _nickTextFiled.returnKeyType = UIReturnKeyDone;
        _nickTextFiled.keyboardType =UIKeyboardTypeDefault;
        _nickTextFiled.font = [UIFont systemFontOfSize:16.f];
        _nickTextFiled.textColor = RGBACOLOR(51, 51, 51,1);
    }
    return _nickTextFiled;
}

-(UILabel *)restrictLabel{
    if (!_restrictLabel) {
        _restrictLabel= [[UILabel alloc] init];
        _restrictLabel.text =@"昵称不能超过20个字";
        _restrictLabel.textColor = RGBACOLOR(102, 102, 102,1);
        _restrictLabel.font =[UIFont systemFontOfSize:14];
    }
    return _restrictLabel;
}

-(UIButton *)saveBtn{
    if (!_saveBtn) {
        _saveBtn =[UIButton buttonWithType:UIButtonTypeCustom];
        _saveBtn.backgroundColor = MainColor;
        _saveBtn.layer.cornerRadius = 24;
        _saveBtn.layer.masksToBounds = YES;
        _saveBtn.titleLabel.font =[UIFont systemFontOfSize:18];
        [_saveBtn setTitle:@"保存" forState:UIControlStateNormal];
        [_saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_saveBtn addTarget:self action:@selector(gotoAmendNickname) forControlEvents:UIControlEventTouchUpInside];
    }
    return _saveBtn;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
